﻿using System.Security.Principal;
using System.Threading.Tasks;

namespace Sidvall.Security
{
    public class UserManager
    {
        #region Public Members

        public Sidvall.Security.IUserProvider UserProvider { get; set; }
        #region PrincipalManager

        private PrincipalManager _PrincipalManager;
        public PrincipalManager PrincipalManager
        {
            get
            {
                if (_PrincipalManager != null)
                    return _PrincipalManager;
                return Sidvall.SystemContext.Current.PrincipalManager;
            }
            set
            {
                _PrincipalManager = value;
            }
        }

        #endregion

        #region GetUserItemAsync

        public async Task<UserItem> GetUserItemAsync()
        {
            return await GetUserItemAsync(this.PrincipalManager.CurrentPrincipal).ConfigureAwait(false);
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public async Task<UserItem> GetUserItemAsync(IPrincipal principal)
        {
            if (principal == null)
                return null;
            return await GetUserItemAsync(principal.Identity).ConfigureAwait(false);
        }
        public async Task<UserItem> GetUserItemAsync(IIdentity identity)
        {
            if (identity == null)
                return null;
            if (this.UserProvider == null)
                return null;
            return await this.UserProvider.GetUserItemAsync(identity).ConfigureAwait(false);
        }

        #endregion
        #region SaveUserItemAsync

        public async Task<UserItem> SaveUserItemAsync(UserItem item)
        {
            if (this.UserProvider == null)
                return item;
            return await this.UserProvider.SaveUserItemAsync(item).ConfigureAwait(false);
        }

        #endregion

        #region ToString

        public override string ToString()
        {
            return "UserManager - Sidvall.Security.IUserProvider";
        }

        #endregion

        #endregion
        #region Constructors

        public UserManager(Sidvall.Security.IUserProvider userProvider)
        {
            this.UserProvider = userProvider;
        }
        public UserManager(Sidvall.Security.IUserProvider userProvider, PrincipalManager principalManager)
        {
            this.UserProvider = userProvider;
            this.PrincipalManager = principalManager;
        }

        #endregion
    }
}
